import 'package:flutter/material.dart';
import '../widgets/responsive_widgets.dart';
import '../widgets/product_card.dart';

/// 商品页面
/// 展示商品列表，支持筛选、排序和商品详情查看
/// 学习StatefulWidget、GridView、FilterChip、DropdownButton等Widget的使用
class ProductScreen extends StatefulWidget {
  const ProductScreen({super.key});

  @override
  State<ProductScreen> createState() => _ProductScreenState();
}

/// 商品页面的状态管理类
class _ProductScreenState extends State<ProductScreen> {
  /// 当前选中的商品分类
  String _selectedCategory = '全部';

  /// 当前选中的排序方式
  String _sortBy = '默认';

  /// 商品分类列表
  final List<String> categories = ['全部', '手机', '电脑', '耳机', '手表', '相机'];

  /// 排序选项列表
  final List<String> sortOptions = ['默认', '价格升序', '价格降序', '销量', '评分'];

  @override
  Widget build(BuildContext context) {
    // 获取屏幕尺寸信息，用于响应式设计
    final screenSize = MediaQuery.of(context).size;
    final isTablet = screenSize.width > 600; // 平板断点
    final isDesktop = screenSize.width > 900; // 桌面断点

    return Scaffold(
      appBar: AppBar(
        title: const Text('商品列表'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        elevation: 0, // 移除阴影，使用Material 3风格
        actions: [
          // 搜索按钮
          IconButton(icon: const Icon(Icons.search), onPressed: () {}),
          // 筛选按钮
          IconButton(icon: const Icon(Icons.filter_list), onPressed: () {}),
        ],
      ),
      body: Column(
        children: [
          // 筛选栏 - 包含分类选择和排序选项
          _buildFilterBar(context, isTablet),

          // 商品网格 - 展示商品列表
          Expanded(child: _buildProductGrid(context, isTablet, isDesktop)),
        ],
      ),
    );
  }

  /// 构建筛选栏
  /// 包含分类选择和排序选项，使用FilterChip和DropdownButton
  Widget _buildFilterBar(BuildContext context, bool isTablet) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        border: Border(
          bottom: BorderSide(
            color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
          ),
        ),
      ),
      child: Column(
        children: [
          // 分类选择行
          Row(
            children: [
              Text(
                '分类: ',
                style: Theme.of(
                  context,
                ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
              ),
              // 水平滚动的分类标签
              Expanded(
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: categories.map((category) {
                      final isSelected = _selectedCategory == category;
                      return Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: FilterChip(
                          label: Text(category),
                          selected: isSelected,
                          onSelected: (selected) {
                            setState(() {
                              _selectedCategory = category;
                            });
                          },
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          // 排序选择行
          Row(
            children: [
              Text(
                '排序: ',
                style: Theme.of(
                  context,
                ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
              ),
              // 下拉选择排序方式
              Expanded(
                child: DropdownButton<String>(
                  value: _sortBy,
                  isExpanded: true, // 占满剩余空间
                  underline: Container(), // 移除下划线
                  items: sortOptions.map((option) {
                    return DropdownMenuItem(value: option, child: Text(option));
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      _sortBy = value!;
                    });
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 商品网格
  Widget _buildProductGrid(
    BuildContext context,
    bool isTablet,
    bool isDesktop,
  ) {
    final products = [
      {
        'name': 'iPhone 15 Pro Max',
        'price': '¥9999',
        'image': '📱',
        'rating': 4.8,
      },
      {
        'name': 'MacBook Pro 14"',
        'price': '¥14999',
        'image': '💻',
        'rating': 4.9,
      },
      {'name': 'AirPods Pro 2', 'price': '¥1999', 'image': '🎧', 'rating': 4.7},
      {
        'name': 'Apple Watch Series 9',
        'price': '¥2999',
        'image': '⌚',
        'rating': 4.6,
      },
      {
        'name': 'iPad Pro 12.9"',
        'price': '¥6799',
        'image': '📱',
        'rating': 4.8,
      },
      {
        'name': 'Sony WH-1000XM5',
        'price': '¥2899',
        'image': '🎧',
        'rating': 4.9,
      },
      {
        'name': 'Samsung Galaxy S24',
        'price': '¥6999',
        'image': '📱',
        'rating': 4.7,
      },
      {'name': 'Dell XPS 13', 'price': '¥8999', 'image': '💻', 'rating': 4.6},
    ];

    // 根据筛选条件过滤商品
    List<Map<String, dynamic>> filteredProducts = products;
    if (_selectedCategory != '全部') {
      // 这里可以根据实际需求实现分类过滤逻辑
    }

    // 根据排序条件排序商品
    switch (_sortBy) {
      case '价格升序':
        filteredProducts.sort(
          (a, b) => double.parse(
            a['price'].substring(1),
          ).compareTo(double.parse(b['price'].substring(1))),
        );
        break;
      case '价格降序':
        filteredProducts.sort(
          (a, b) => double.parse(
            b['price'].substring(1),
          ).compareTo(double.parse(a['price'].substring(1))),
        );
        break;
      case '评分':
        filteredProducts.sort(
          (a, b) => (b['rating'] as double).compareTo(a['rating'] as double),
        );
        break;
    }

    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: isDesktop
            ? 4
            : isTablet
            ? 3
            : 2,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 0.75,
      ),
      itemCount: filteredProducts.length,
      itemBuilder: (context, index) {
        final product = filteredProducts[index];
        return ProductCard(
          name: product['name']!,
          price: product['price']!,
          image: product['image']!,
          onTap: () {
            _showProductDetail(context, product);
          },
        );
      },
    );
  }

  // 显示商品详情
  void _showProductDetail(BuildContext context, Map<String, dynamic> product) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => DraggableScrollableSheet(
        initialChildSize: 0.7,
        minChildSize: 0.5,
        maxChildSize: 0.95,
        builder: (context, scrollController) {
          return Container(
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            child: Column(
              children: [
                // 拖拽指示器
                Container(
                  margin: const EdgeInsets.only(top: 8),
                  width: 40,
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
                // 商品详情内容
                Expanded(
                  child: SingleChildScrollView(
                    controller: scrollController,
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 商品图片
                        Center(
                          child: Container(
                            width: 200,
                            height: 200,
                            decoration: BoxDecoration(
                              color: Theme.of(
                                context,
                              ).colorScheme.primaryContainer,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Center(
                              child: Text(
                                product['image']!,
                                style: const TextStyle(fontSize: 80),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(height: 20),
                        // 商品名称
                        Text(
                          product['name']!,
                          style: Theme.of(context).textTheme.headlineSmall
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 8),
                        // 价格
                        Text(
                          product['price']!,
                          style: Theme.of(context).textTheme.headlineMedium
                              ?.copyWith(
                                color: Theme.of(context).colorScheme.primary,
                                fontWeight: FontWeight.bold,
                              ),
                        ),
                        const SizedBox(height: 16),
                        // 评分
                        Row(
                          children: [
                            ...List.generate(5, (index) {
                              return Icon(
                                index < (product['rating'] as double).floor()
                                    ? Icons.star
                                    : Icons.star_border,
                                color: Colors.amber,
                                size: 20,
                              );
                            }),
                            const SizedBox(width: 8),
                            Text(
                              '${product['rating']}',
                              style: Theme.of(context).textTheme.bodyMedium,
                            ),
                          ],
                        ),
                        const SizedBox(height: 20),
                        // 购买按钮
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context);
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  content: Text('已添加到购物车: ${product['name']}'),
                                  action: SnackBarAction(
                                    label: '查看购物车',
                                    onPressed: () {},
                                  ),
                                ),
                              );
                            },
                            style: ElevatedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(vertical: 16),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                            child: const Text(
                              '加入购物车',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
